<template>
	<!-- 编辑弹出框 -->
	<el-dialog :title="dialogTitle" v-model="dialogVisible" :close-on-click-modal="false" width="400px">
		<el-form ref="theFormRef" :model="dataForm" :rules="rules" label-width="70px">
			<el-form-item label="用户Id"><el-input v-model="dataForm.id" :disabled="true"></el-input></el-form-item>
			<el-form-item label="用户名" prop="name"><el-input v-model="dataForm.name"></el-input></el-form-item>
			<el-form-item label="邮件" prop="email"><el-input v-model="dataForm.email"></el-input></el-form-item>
			<el-form-item label="电话" prop="phone"><el-input v-model="dataForm.phone"></el-input></el-form-item>
			<el-form-item label="性别">
				<el-radio-group v-model="dataForm.gender">
					<el-radio :label="1">男</el-radio>
					<el-radio :label="0">女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="昵称"><el-input v-model="dataForm.nickName"></el-input></el-form-item>
			<el-form-item label="头像"><upload-single-image v-model="dataForm.avatar"></upload-single-image></el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleSubmit">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
import * as UserAPI from '@/api/user.js';
import UploadSingleImage from '@/components/Upload/UploadSingleImage.vue';

import { ref, reactive, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
const dialogVisible = ref(false);
const dataForm = ref({ id: 0 });

//数据校验规则，后续继续完善
const rules = reactive({
	name: [
		{
			required: true,
			message: '用户名不能为空',
			trigger: 'blur'
		}
	],
	phone: [
		{
			required: true,
			message: '手机号不能为空',
			trigger: 'change'
		}
	],
	email: [
		{
			required: true,
			message: '邮箱不能为空',
			trigger: 'blur'
		}
	]
});

//弹框标题
const dialogTitle = computed(() => {
	return !dataForm.value.id ? '新增' : '编辑';
});
//声明一个模板中DOM元素的引用, 必须和模板里的 ref 同名
const theFormRef = ref(null);
const emit = defineEmits(['refreshDataList']);

const init = async id => {
	dataForm.value.id = id || 0;
	dialogVisible.value = true;
	await nextTick();
	theFormRef.value.resetFields();
	if (id) {
		//是编辑
		let result = await UserAPI.getDetailById(id);
		dataForm.value = result.data; //看接口文档，知道data是对应的用户对象
	} else {
		//是新增
		ElMessage.warning(`管理员不能新增注册用户！`);
	}
};

// 确认提交
const handleSubmit = () => {
	if (!theFormRef.value) return
	theFormRef.value.validate(async (valid, fields) => {
		if (valid) {
			await UserAPI.update(dataForm.value);
			ElMessage.success(`保存成功`);
			dialogVisible.value = false;
			emit('refreshDataList'); //重新刷新列表数据
		}else{
			console.log('error submit!', fields)
		}
	});
};

//暴露接口方法
defineExpose({
	init
});

</script>

<style scoped></style>
